//
//  ZLAlertText.swift
//  ZLAlert
//
//  Created by 赵振磊 on 2022/11/27.
//

import Foundation
/// 编辑
public typealias ZLAlertEditChange = (_ text: String) -> Void
/// 编辑完成
public typealias ZLAlertEditEnd = (_ text: String) -> Void
class ZLAlertTextField: UITextField {
    /// 编辑改变
    public var editChange: ZLAlertEditChange?
    /// 编辑完成
    public var editEnd: ZLAlertEditEnd?
    /// 提交回调
    public var submitCallBack: ZLAlertEditEnd? {
        didSet {
            NotificationCenter.default.addObserver(self, selector: #selector(callTextFieldNotif), name: NSNotification.Name(rawValue: "ZLAlertCallTextField"), object: nil)
        }
    }
    /// 创建输入框
    /// - Parameters:
    ///   - text: 默认内容
    ///   - placeholder: 提示
    ///   - config: 配置
    /// - Returns: ZLAlertTextField
    class func zl_textField(_ text: String, _ placeholder: String, _ config: ZLAlertItemConfig) -> ZLAlertTextField {
        let textField = ZLAlertTextField()
        textField.text = text
        textField.font = config.font
        textField.textColor = config.color
        textField.placeholder = placeholder
        textField.textAlignment = config.alignment
        textField.backgroundColor = config.backgroundColor
        textField.layer.cornerRadius = config.cornerRadius
        textField.layer.borderWidth = config.borderWidth
        textField.layer.borderColor = config.borderColor.cgColor
        return textField
    }
    
    
    @objc func callTextFieldNotif() {
        if self.submitCallBack != nil {
            self.submitCallBack!(self.text ?? "")
        }
    }
}

extension ZLAlert {
    /// 添加输入框
    /// - Parameters:
    ///   - placeholder: 提示
    ///   - submit: 提交回调
    /// - Returns: ZLAlert
    @discardableResult
    public func addTextField(_ placeholder: String, submit: ZLAlertEditEnd?) -> ZLAlert {
        return self.addTextField("", placeholder, ZLAlertConfig.shared.inputConfig, editChange: nil, editEnd: nil, submit: submit)
    }
    /// 添加输入框
    /// - Parameters:
    ///   - placeholder: 提示
    ///   - editEnd: 编辑完成回调
    /// - Returns: ZLAlert
    @discardableResult
    public func addTextField(_ placeholder: String, editEnd: ZLAlertEditEnd?) -> ZLAlert {
        return self.addTextField("", placeholder, ZLAlertConfig.shared.inputConfig, editChange: nil, editEnd: editEnd, submit: nil)
    }
    /// 添加输入框
    /// - Parameters:
    ///   - placeholder: 提示
    ///   - editChange: 编辑改变回调
    ///   - editEnd: 编辑完成回调
    ///   - submit: 提交回调
    /// - Returns: ZLAlert
    @discardableResult
    public func addTextField(_ placeholder: String, editChange: ZLAlertEditChange?, editEnd: ZLAlertEditEnd?, submit: ZLAlertEditEnd?) -> ZLAlert {
        return self.addTextField("", placeholder, ZLAlertConfig.shared.inputConfig, editChange: editChange, editEnd: editEnd, submit: submit)
    }
    /// 添加输入框
    /// - Parameters:
    ///   - text: 默认内容
    ///   - placeholder: 提示
    ///   - config: 配置
    ///   - editChange: 输入框内容变化
    ///   - editEnd: 输入结束
    /// - Returns: ZLAlert
    @discardableResult
    public func addTextField(_ text: String, _ placeholder: String, _ config: ZLAlertItemConfig, editChange: ZLAlertEditChange?, editEnd: ZLAlertEditEnd?, submit: ZLAlertEditEnd?) -> ZLAlert {
        let lastView = self.mainView.subviews.last
        let textField = ZLAlertTextField.zl_textField(text, placeholder, config)
        textField.editChange = editChange
        textField.editEnd = editEnd
        textField.submitCallBack = submit
        textField.delegate = self
        self.mainView.addSubview(textField)
        textField.snp.makeConstraints { make in
            make.left.equalTo(self.mainView).offset(config.insets.left)
            make.right.equalTo(self.mainView).offset(-config.insets.right)
            if (lastView == nil) {
                make.top.equalTo(self.mainView).offset(config.insets.top)
            } else {
                make.top.equalTo(lastView!.snp.bottom).offset(config.insets.top)
            }
            make.height.equalTo(config.height)
        }
        return self.layoutMainView(0)
    }
    
    /// 键盘弹起
    @objc func keyboardWillShow(_ notification: NSNotification) {
        if (self.mainView.textField == nil) {
            return
        }
        let rect1 = self.mainView.textField!.convert(self.mainView.textField!.frame, from: self.mainView)
        let rect = self.mainView.textField?.convert(rect1, to: self.view)
        if let userInfo = notification.userInfo,
           let value = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue,
           let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
           let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
            let frame = value.cgRectValue
            let intersection = CGRectIntersection(frame, self.view.frame)
            let deltaY = CGRectGetHeight(intersection) - (self.view.zl_height - CGRectGetMaxY(rect!))
            if deltaY < 0 {
                return
            }
            UIView.animate(withDuration: duration, delay: 0.0,
                           options: UIView.AnimationOptions(rawValue: curve),
                           animations: {
                self.view.frame = CGRectMake(0,-deltaY,self.view.bounds.width,self.view.bounds.height)
                self.view.layoutIfNeeded()
            }, completion: nil)
        }
    }
    @objc func keyboardWillHide(_ notification: NSNotification) {
        if let userInfo = notification.userInfo,
           let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
           let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
            UIView.animate(withDuration: duration, delay: 0.0,
                           options: UIView.AnimationOptions(rawValue: curve),
                           animations: {
                self.view.frame = self.view.bounds
                self.view.layoutIfNeeded()
            }, completion: nil)
        }
    }
    @objc func keyboardDidHide(_ notification: NSNotification) {
        self.mainView.textField = nil
    }
}

extension ZLAlert: UITextFieldDelegate {
    public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        self.mainView.textField = textField
        return true
    }
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (!textField.isKind(of: ZLAlertTextField.self)) {
            return false
        }
        let zlTextField = textField as! ZLAlertTextField
        if (zlTextField.editChange != nil) {
            zlTextField.editChange!(textField.text ?? "")
        }
        return true
    }
    public func textFieldDidEndEditing(_ textField: UITextField) {
        if (!textField.isKind(of: ZLAlertTextField.self)) {
            return
        }
        let zlTextField = textField as! ZLAlertTextField
        if (zlTextField.editEnd != nil) {
            zlTextField.editEnd!(textField.text ?? "")
        }
    }
}
